package com.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;

import static com.util.DateUtils.FORMAT_yyyyMMdd;

public class IdCardUtil {

    /**
     * 18位身份证获取性别和年龄
     * @param idCard
     * @return
     * @throws Exception
     */
    public static Integer identityCard18(String idCard) {
        if (StringUtils.isEmpty(idCard) || idCard.length() != 18) {
            return null;
        }
        try {
            return getAge(DateUtils.parseDate(idCard.substring(6, 14), FORMAT_yyyyMMdd));           //由出生日期获得年龄***
        } catch (Exception e) {
            return null;
        }
    }

    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前，年龄减一
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

    public static void main(String[] args) {
        try {
            Integer age = identityCard18("232323198809090215");

            System.out.println("age:"+age);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

}
